<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
require_once (_PS_CLASS_DIR_ . 'FrontController.php');
include_once(dirname(__FILE__)."/../Zadmindepartment.php");
include_once(dirname(__FILE__)."/../ZadminPriority.php");
include_once(dirname(__FILE__)."/../classes/ZticketObject.php");
include_once(dirname(__FILE__)."/../ZadminRating.php");

class ZhelpdeskDetailTicketController extends FrontControllerCore {
	private $id_ticket=null;
	private $complete=null;
	public function __construct() { 
		parent::__construct();
		$this->id_ticket = Tools::getValue ('ticket',1);
	}
	
    public function setMedia() {
    	parent::setMedia();
    	Tools::addCSS(_MODULE_DIR_.'/zhelpdesk/css/detail-ticket.css');
    	Tools::addJS(_MODULE_DIR_.'/zhelpdesk/js/detail-ticket.js');
    	Tools::addJS(__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js');
    }

    public function preProcess() {
    	$obj = new ZTicketObject ($this->id_ticket);
    	
    	
		if (Tools::isSubmit('submitReplyTicket')) {
			if (Tools::getValue('content')=='') 
				$this->errors[] = Tools::displayError('This <b>content</b> is require.');
			else {
				$content = Tools::getValue ('content');
				if ($fileimg = $_FILES['attached_files']['name']) {
					$obj->setMessageForTicket ($content,$fileimg);
				} else 
					$obj->setMessageForTicket ($content);
				$this->complete =1;
				$obj->id_zhelpdesk_ticket_status=1;
				$result = $obj->save();
				
				/* ----getway send mail when customer reply to staff| Status ticket -> open--------- */
				$employee = new EmployeeCore ($obj->id_staff);
				$name = $employee->firstname." ".$employee->lastname;
				$textbody = Configuration::get('UD_TICKET_TEMPLATE_FOR_STAFF',Configuration::get('PS_LANG_DEFAULT'));
				
				if ($textbody == '')
					$textbody = 'You\'ve been had reply customer,<p>Ticket is sent from the client name {name_customer}, email {email_customer}</p><p>{content}</p><p>Please reply to this email within 24 hours</p>';
				
				$words = array (
					'{name_customer}' => $obj->name_customer,
					'{email_customer}' => $obj->email_customer,
					'{content}' => $content
				);
				
				$rs = ZticketObject::sendMailTo ($employee->email,$name,$obj->subject,$textbody,$words);
				/* ----getway send mail when add new ticket------------- */
			}
			
		}
		
		self::$smarty->assign(array(
			'hasError' => !empty($this->errors),
			'errors' => $this->errors,
			'complete' => $this->complete
		));
		
		parent::preProcess();
    }
    
/**
     * see parent
     * Change get n default 
     */
	public function pagination($nbProducts = 10)
	{
		if (!self::$initialized)
			$this->init();

		$nArray = (int)(Configuration::get('PS_PRODUCTS_PER_PAGE')) != 10 ? array((int)(Configuration::get('PS_PRODUCTS_PER_PAGE')), 10, 20, 50) : array(10, 20, 50);
		asort($nArray);
		$this->n = abs((int)(Tools::getValue('n', ((isset(self::$cookie->nb_item_per_page) AND self::$cookie->nb_item_per_page >= 10) ? self::$cookie->nb_item_per_page : (int)(Configuration::get('ZHD_NB_MESS_D_TICKET'))))));
		$this->p = abs((int)(Tools::getValue('p', 1)));
		
		$current_url = tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']);
		//delete parameter page
		$current_url = preg_replace('/(\?)?(&amp;)?p=\d+/', '$1', $current_url);
		
		$range = 2; /* how many pages around page selected */

		if ($this->p < 0)
			$this->p = 0;

		if (isset(self::$cookie->nb_item_per_page) AND $this->n != self::$cookie->nb_item_per_page AND in_array($this->n, $nArray))
			self::$cookie->nb_item_per_page = $this->n;

		if ($this->p > ($nbProducts / $this->n))
			$this->p = ceil($nbProducts / $this->n);
		$pages_nb = ceil($nbProducts / (int)($this->n));

		$start = (int)($this->p - $range);
		if ($start < 1)
			$start = 1;
		$stop = (int)($this->p + $range);
		if ($stop > $pages_nb)
			$stop = (int)($pages_nb);
		self::$smarty->assign('nb_products', $nbProducts);
		$pagination_infos = array(
			'products_per_page' => (int)Configuration::get('PS_PRODUCTS_PER_PAGE'),
			'pages_nb' => $pages_nb,
			'p' => $this->p,
			'n' => $this->n,
			'nArray' => $nArray,
			'range' => $range,
			'start' => $start,
			'stop' => $stop,
			'current_url' => $current_url
		);
		self::$smarty->assign($pagination_infos);
	}
    
    /**
     * display content
     */
    public function displayContent() {
    	$p = Tools::getValue('p',1);
    	$n = Tools::getValue('n',Configuration::get('ZHD_NB_MESS_D_TICKET'));
    	$messages = ZTicketObject::getAllMessageForTicket ($this->id_ticket,$p,$n);
    	$nbMessage=ZTicketObject::getNumberMessageTicket($this->id_ticket);
    	$this->pagination ($nbMessage);
    	$ratings = ZratingObject::getAllRatings (self::$cookie->id_lang);
    	$ticket = ZTicketObject::getInfoTicket($this->id_ticket,self::$cookie->id_lang);
    	$link = Tools::getShopDomain(true).__PS_BASE_URI__.'modules/zhelpdesk/zhelpdesk-ticket.php';
    	$id_customer = (!$id_customer = (int)self::$cookie->id_customer) ? false : (int)self::$cookie->id_customer;
    	/*for Editor MCE*/
    	$iso = Language::getIsoById((int)(self::$cookie->id_lang));
		$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
		$ad = dirname($_SERVER["PHP_SELF"]);
		/*end for Editor MCE*/
    	self::$smarty->assign(array(
			'messages'=> $messages,
    		'ad' => $ad,
    		'iso' => $iso,
    		'pathCSS' => _THEME_CSS_DIR_,
    		'ticket' => $ticket,
    		'id_ticket' => $this->id_ticket,
    		'_PS_IMG_' => _PS_IMG_,
    		'_MODULE_DIR_' => _MODULE_DIR_,
    		'nb_products' => $nbMessage,
    		'ratings' => $ratings,
    		'id_customer' => $id_customer,
    		'path' => '<a title="Ticket List" href="'.$link.'">Ticket List</a><span class="navigation-pipe">&gt;</span>Detail Ticket'
		));
        self::$smarty->display(_PS_MODULE_DIR_ . 'zhelpdesk/themes/detail-ticket.tpl');
    }    
}
